package high.concurent.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import high.concurent.dao.AddressMapper;
import high.concurent.model.AddressDO;
import high.concurent.request.AddressRequest;
import high.concurent.service.AddressService;
import high.concurent.vo.AddressVO;
import high.concurrent.enums.AddressStatusEnum;
import high.concurrent.enums.BizCodeEnum;
import high.concurrent.interceptor.UserInterceptor;
import high.concurrent.model.LoginUser;
import high.concurrent.utils.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AddressServiceImpl implements AddressService {

    @Autowired(required = false)
    private AddressMapper addressMapper;

    /**
     * 根据地址ID获取地址信息
     * @param addressId 地址ID
     * @return
     */
    @Override
    public JsonData getAddressById(Long addressId) {

        // 从threadLocal中获取解析token获取的用户信息，判断是否存在
        LoginUser loginUser = UserInterceptor.threadLocal.get();
        if(loginUser == null){
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN);
        }
        // mybatis-plus根据addressId查询地址
        AddressDO addressDO = addressMapper.selectOne(new QueryWrapper<AddressDO>()
                .eq("id", addressId)
                .eq("user_id", loginUser.getId()));

        // 创建VO值传递对象
        AddressVO addressVO = new AddressVO();
        // 当返回数据不为空，则把内容复制给VO返回
        if(addressDO != null){
            BeanUtils.copyProperties(addressDO, addressVO);
            return JsonData.buildSuccess(addressVO);
        }

        return JsonData.buildResult(BizCodeEnum.ADDRESS_NO_EXITS);
    }


    /**
     * 新增收货地址
     * @param addressRequest 地址信息
     * @return
     */
    @Override
    public JsonData insertAddress(AddressRequest addressRequest) {

        // 从threadLocal中获取解析token获取的用户信息，判断是否存在
        LoginUser loginUser = UserInterceptor.threadLocal.get();
        if(loginUser == null){
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN);
        }

        // 把前端参数注入DO数据库映射对象
        AddressDO addressDO = new AddressDO();
        BeanUtils.copyProperties(addressRequest, addressDO);
        addressDO.setCreateTime(new Date());
        addressDO.setUserId(loginUser.getId());

        // 当用户将新增地址设为收货地址时， 判断库内是否存在默认收货地址
        if(addressRequest.getDefaultStatus() == 1) {
           this.checkAdderssDefaultStatus(loginUser);
        }

        // 新增地址插入数据库
        int rows = addressMapper.insert(addressDO);
        log.info("新增收货地址成功: row = {}, 信息={}", rows, addressDO);

        return  rows == 1 ? JsonData.buildSuccess() : JsonData.buildResult(BizCodeEnum.ADDRESS_ADD_FAIL);
    }


    /**
     * 根据【地址id】与【用户id】删除地址
     * @param addressId 地址id
     * @return
     */
    @Override
    public JsonData deleteAddress(Long addressId) {

        // 从threadLocal中获取解析token获取的用户信息，判断是否存在
        LoginUser loginUser = UserInterceptor.threadLocal.get();
        if(loginUser == null){
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN);
        }

        // 删除地址
        int rows = addressMapper.delete(new QueryWrapper<AddressDO>()
                .eq("id", addressId)
                // 删除地址这里一定要加【user_id】条件，防止token被盗，黑客进行水平越权攻击，更改他人地址
                .eq("user_id", loginUser.getId()));

        return rows == 1 ? JsonData.buildSuccess() : JsonData.buildResult(BizCodeEnum.ADDRESS_DEL_FAIL);
    }


    /**
     * 查询用户全部收货地址
     * @return
     */
    @Override
    public JsonData searchAllAddressList() {

        // 从threadLocal中获取解析token获取的用户信息，判断是否存在
        LoginUser loginUser = UserInterceptor.threadLocal.get();
        if(loginUser == null){
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN);
        }

        // 根据用户id查询所有地址
        List<AddressDO> listAddressDOs = addressMapper.selectList(new QueryWrapper<AddressDO>()
                .eq("user_id", loginUser.getId()));

        // 把数据库映射DO类型，转换成VO返回给前端
        List<AddressVO> listAddressVOs = listAddressDOs.stream().map(addressDO -> {
            AddressVO addressVO = new AddressVO();
            BeanUtils.copyProperties(addressDO, addressVO);
            return addressVO;
        }).collect(Collectors.toList());

        return JsonData.buildSuccess(listAddressVOs);
    }


    /**
     * 判断库中是否存在默认收货地址，若存在则改为非收货地址
     * @param loginUser
     */
    private void checkAdderssDefaultStatus(LoginUser loginUser){

        // 判断数据库当前是否有默认收货地址
        AddressDO checkDefaultAddress = addressMapper.selectOne(new QueryWrapper<AddressDO>()
                .eq("user_id", loginUser.getId())
                .eq("default_status", AddressStatusEnum.DEFAULT_ADDRESS.getStatus()));

        // 如果不为空，则更改该地址为【非默认收货地址】
        if(checkDefaultAddress != null){
            checkDefaultAddress.setDefaultStatus(AddressStatusEnum.NORMAL_ADDRESS.getStatus());
            addressMapper.update(checkDefaultAddress, new QueryWrapper<AddressDO>()
                    .eq("id",checkDefaultAddress.getId())
                    // 修改地址这里一定要加【user_id】条件，防止token被盗，黑客进行水平越权攻击，更改他人地址
                    .eq("user_id", loginUser.getId()));
        }
    }


}
